package com.ruoyi.web.controller.business.rule.factory;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.order.domain.JbOrder;
import com.ruoyi.business.rule.domain.JbOrderCoefficientRules;
import com.ruoyi.business.rule.service.JbOrderCoefficientRulesService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.web.controller.business.order.factory.JbOrderFactory;
import com.ruoyi.web.controller.system.factory.SysUserFactory;
import com.ruoyi.web.core.JoController;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 业务 订单提成by部门 工厂
 *
 * @author Jyl
 */
@Log4j2
@Component
public class JbOrderCoefficientRulesFactory extends JoController
{

    @Autowired
    private JbOrderCoefficientRulesService jbOrderCoefficientRulesService;
    @Autowired
    private JbOrderFactory jbOrderFactory;
    @Autowired
    private SysUserFactory sysUserFactory;

    /**
     * 查询 当前登录人所属部门规则
     *
     * @param orderId 订单主键
     * @return
     */
    public JbOrderCoefficientRules findByDeptAncestors(Long orderId)
    {
        List<String> deptId = getOrderCreatByDeptId(orderId);
        return jbOrderCoefficientRulesService.getOne(new LambdaQueryWrapper<JbOrderCoefficientRules>()
                .in(JbOrderCoefficientRules::getDeptId, deptId)
        );
    }

    /**
     * 获取 部门信息
     *
     * @param orderId 订单主键
     * @return
     */
    public List<String> getOrderCreatByDeptId(Long orderId)
    {
        List<String> deptIds = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(orderId))
        {
            //订单主键不为空， 且能查询到创建人，获取部门信息
            JbOrder jbOrder = jbOrderFactory.getService().getById(orderId);
            if (ObjectUtil.isNotEmpty(jbOrder))
            {
                Long userId = jbOrder.getCreateBy();
                SysUser sysUser = sysUserFactory.getSysUser(userId);
                Long deptId = sysUser.getDeptId();

                deptIds = StrUtil.split(sysUser.getDept().getAncestors(), ",");
                deptIds.add(deptId + "");
                return deptIds;
            }
        }

        // 无法从订单获取部门信息， 以当前登录人信息为准
        deptIds = StrUtil.split(getUser().getDept().getAncestors(), ",");
        deptIds.add(getUser().getDept().getDeptId() + "");
        return deptIds;
    }
}
